<?php

namespace app\api\service\shop;

use app\admin\model\factor\CarbonFactor;
use app\admin\model\factor\FactorCollection;
use think\Model;

/**
 * 因子收藏服务类
 */
class FactorCollectionService
{

    /**
     * 因子收藏
     * @param int $userId 用户ID
     * @param int $factorId 产品ID
     * @return string | null     收藏成功返回null, 失败返回提示信息
     */
    public function factorCollection(int $userId, int $factorId): ?string
    {
        $where = ['user_id' => $userId, 'factor_id' => $factorId];
        $factorInfo = $this->getFactorInfo($factorId);
        if (is_null($factorInfo)) return '当前因子数据不存在或未上架';
        if ($factorInfo['user_id'] == $userId) return '请不要收藏自己创建的数据因子';
        $factorCollection = FactorCollection::where($where)->find();
        if (!is_null($factorCollection)) return '该因子已收藏';
        $factorCollection = FactorCollection::create($where);
        return !$factorCollection ? '收藏失败!' : null;
    }

    /**
     * 获取因子信息
     * @param int $factorId
     */
    public function getFactorInfo(int $factorId): ?Model
    {
        return CarbonFactor::where(['id' => $factorId, 'status' => 1])->field(['id', 'user_id'])->find();
    }

    /**
     * 取消因子收藏
     * @param int $userId 用户ID
     * @param int $factorId 产品ID
     * @return string | null     取消成功返回null, 失败返回提示信息
     */
    public function cancelFactorCollection(int $userId, int $factorId): ?string
    {
        $where = ['user_id' => $userId, 'factor_id' => $factorId];
        $factorCollection = FactorCollection::where($where)->find();
        if (is_null($factorCollection)) return '当前产品没有被收藏';
        $factorCollection = FactorCollection::where($where)->delete();
        return !$factorCollection ? '取消收藏失败!' : null;
    }

}